<template>
  <div>
    <!-- 筛选与操作区域 -->
    <a-card title="碳排放审核" bordered style="margin-bottom: 10px">
      <a-row :gutter="16" align="middle">
        <a-col span="8">
          <a-form-item label="审计类型">
            <a-select v-model="auditType" placeholder="选择审计类型" style="width: 100%">
              <a-select-option value="internal">公司内部审计</a-select-option>
              <!-- 其他选项可以添加在这里 -->
            </a-select>
          </a-form-item>
        </a-col>
        <a-col span="8">
          <a-form-item label="审计日期">
            <a-date-picker v-model="date" style="width: 100%" placeholder="选择日期" />
          </a-form-item>
        </a-col>
        <a-col span="8">
          <a-form-item>
            <a-button type="primary" @click="filter">筛选</a-button>
            <a-button type="default" style="margin-left: 8px" @click="showAddModal"
              >新增报告</a-button
            >
          </a-form-item>
        </a-col>
      </a-row>
      <a-checkbox v-model="showDeleted" style="margin-top: 10px">查看已删除</a-checkbox>
    </a-card>

    <!-- 数据表格区域 -->
    <a-card title="审计记录" bordered>
      <a-table
        :dataSource="auditData"
        :columns="columns"
        rowKey="id"
        :pagination="{ pageSize: 5 }"
        :scroll="{ x: 2400 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="edit(record)">修改</a-button>
              <a-button type="link" danger @click="deleteRecord(record)">删除</a-button>
            </a-space>
          </template>
          <template v-else>
            {{ record[column.dataIndex] }}
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑审计报告模态框 -->
    <a-modal
      v-model:open="isModalVisible"
      title="新增/编辑碳排放报告"
      @ok="save"
      @cancel="resetForm"
    >
      <a-form layout="vertical">
        <a-form-item label="审计类型">
          <a-input v-model:value="addform.auditType" placeholder="请输入审计类型" />
        </a-form-item>
        <a-form-item label="排放源名称">
          <a-select v-model:value="addform.sourceId" placeholder="选择车辆类型">
            <a-select-option v-for="i in data" :key="i.sourceId" :value="i.sourceId">
              {{ i.sourceName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="碳排放量">
          <a-input v-model:value="addform.emissionValue" placeholder="请输入碳排放量" />
        </a-form-item>
        <a-form-item label="审核状态">
          <a-input v-model:value="addform.status" placeholder="请输入审核状态" />
        </a-form-item>
        <a-form-item label="审核人">
          <a-input v-model:value="addform.auditor" placeholder="请输入审核人" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { examine } from "/@/api/Carbon module/Carbon accounting module/Carbon monitoring/examine";
import { selfSupportApi } from "/@/api/Carbon module/Carbon accounting module/Carbon monitoring/self-support";
import { smartSentry } from "/@/lib/smart-sentry";

const auditType = ref("");
const date = ref(null);
const showDeleted = ref(false);
const isModalVisible = ref(false);
const addform = reactive({
  auditType: "",
  sourceId: "",
  emissionValue: "",
  status: "",
  auditor: "",
});
const queryFormState = reactive({
  pageNum: 1,
  pageSize: 10,
});
const data = ref([]);
const auditData = ref([]);
const total = ref(0);
const queryForm = reactive({ ...queryFormState });

const columns = [
  { title: "id", dataIndex: "auditLogId", fixed: "left" },
  { title: "审计类型", dataIndex: "auditType", fixed: "left" },
  { title: "审计日期", dataIndex: "auditDate", width: 170 },
  { title: "碳排放来源", dataIndex: "sourceName" },
  { title: "碳排放数值", dataIndex: "emissionValue" },
  { title: "报告内容", dataIndex: "reportContent", width: 170 },
  { title: "审计备注", dataIndex: "remarks", width: 170 },
  { title: "审核状态", dataIndex: "status" },
  { title: "审核人", dataIndex: "auditor" },
  { title: "是否已删除", dataIndex: "deleted" },
  { title: "修改人", dataIndex: "modifiedBy" },
  { title: "记录创建时间", dataIndex: "createdAt", width: 170 },
  { title: "记录更新时间", dataIndex: "updatedAt", width: 170 },
  { title: "记录删除时间", dataIndex: "deletedAt", width: 170 },
  { title: "操作", dataIndex: "action", key: "action" },
];

const QueryData = async () => {
  try {
    queryForm.pageNum = queryFormState.pageNum;
    queryForm.pageSize = queryFormState.pageSize;
    const queryResult = await examine.query(queryForm);
    auditData.value = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  }
};

const queryjcdata = async () => {
  try {
    const queryResult = await selfSupportApi.queryData({ pageNum: 1, pageSize: 100 });
    data.value = queryResult.data.list;
  } catch (error) {
    console.error(error);
  }
};

const filter = () => {
  // 筛选逻辑
};
const showAddModal = () => {
  resetForm();
  isModalVisible.value = true;
};
const isEditing = ref(false); // 标记是否为编辑状态
const currentEditId = ref(null); // 当前编辑的记录 ID
const save = async () => {
  try {
    if (isEditing.value) {
      // 编辑逻辑
      await examine.Update({ ...addform.value, id: currentEditId.value }); // 假设有 Update 接口
      isEditing.value = false; // 重置编辑状态
    } else {
      // 添加逻辑
      await examine.Add(addform.value); // 假设有 Add 接口
    }

    // 关闭弹窗，刷新数据
    isModalVisible.value = false;
    QueryData();
    resetForm();
  } catch (error) {
    console.error("保存失败:", error);
  }
};

// 编辑记录
const edit = (record) => {
  isEditing.value = true;
  isModalVisible.value = true;
  currentEditId.value = record.auditLogId;
  // 回显数据到表单
  addform.auditType = record.auditType;
  addform.sourceId = record.sourceName;
  addform.emissionValue = record.emissionValue;
  addform.status = record.status;
  addform.auditor = record.auditor;
};

const deleteRecord = async (record) => {
  try {
    await examine.Delete(record.auditLogId);
    QueryData();
  } catch (error) {
    console.error(error);
  }
};

// 重置表单
const resetForm = () => {
  // 使用重新初始化的方式清空表单内容
  addform.auditType = "";
  addform.sourceId = "";
  addform.emissionValue = "";
  addform.status = "";
  addform.auditor = "";

  currentEditId.value = null;
  isEditing.value = false;
  isModalVisible.value = false;
};

onMounted(() => {
  QueryData();
  queryjcdata();
});
</script>

<style scoped>
a-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
</style>
